﻿using FlexCel.Core;
using FlexCel.XlsAdapter;
using System;
using System.Data;
using System.IO;
using Telerik.Web.UI;

namespace EXAM.Admin.Page_Admin
{
    public partial class Question : System.Web.UI.Page
    {
        string sErr = "";
        string path = "";
        string _db = "EXA";
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                btnAnswer.Enabled = false;
                LoadAnal(cboANAL_Q0, "Q0");
                LoadAnal(cboANAL_Q1, "Q1");
                LoadDataAccess();
                if (Session["question"] != null)
                {
                    SetDataToForm((DTO.QuestionInfo)Session["question"]);
                    lbErr.Text = "";

                }
            }
        }

        private void LoadDataAccess()
        {
            BUS.LIST_DAControl ctr = new BUS.LIST_DAControl();
            cboANAL_Q9.DataSource = ctr.GetAll(ref sErr);
            cboANAL_Q9.DataTextField = "DAG_ID";
            cboANAL_Q9.DataValueField = "DAG_ID";
            cboANAL_Q9.DataBind();
        }
        private void RefreshForm(string val)
        {
            txtID.Text = val;
            txtDescription.Text = val;
            txtExplanation.Text = val;
            txtDifficulty.Value = 0;
            txtTimer.Value = 0;
            imgPic.ImageUrl = val;
            rdlEnabled.SelectedIndex = 0;
            lbErr.Text = val;
            btnAnswer.Enabled = false;
            txtRate.Value = 0;
        }

        private DTO.QuestionInfo GetDataFromForm(DTO.QuestionInfo quesInf)
        {
            if (txtID.Text != "")
                quesInf.ID = Convert.ToInt64(txtID.Text);
            quesInf.Type = cbbType.SelectedValue;
            quesInf.Description = txtDescription.Text;
            quesInf.Explanation = txtExplanation.Text;
            quesInf.Difficulty = txtDifficulty.Text != "" ? Convert.ToInt32(txtDifficulty.Text) : 0;
            quesInf.Timer = txtTimer.Text != "" ? Convert.ToInt32(txtTimer.Text) : 0;
            string[] s = imgPic.ImageUrl.Split('/');

            quesInf.Rate = txtRate.Value.Value;
            if (upPicture.UploadedFiles.Count > 0)
            {
                quesInf.Picture = upPicture.UploadedFiles[0].FileName;
                txtPicture.Text = quesInf.Picture;
            }

            if (upSound.UploadedFiles.Count > 0)
            {
                quesInf.Sound = upSound.UploadedFiles[0].FileName;
                txtSound.Text = quesInf.Sound;
            }

            if (rdlEnabled.SelectedValue == "1")
            {
                quesInf.Enabled = true;
            }
            else
                quesInf.Enabled = false;

            quesInf.ANAL_Q0 = cboANAL_Q0.Text;
            quesInf.ANAL_Q1 = cboANAL_Q1.Text;
            quesInf.ANAL_Q9 = cboANAL_Q9.Text;
            return quesInf;
        }

        private void SetDataToForm(DTO.QuestionInfo quesInf)
        {
            txtID.Text = quesInf.ID.ToString();
            cbbType.Text = quesInf.Type;
            txtDescription.Text = quesInf.Description;
            txtExplanation.Text = quesInf.Explanation;
            txtDifficulty.Text = quesInf.Difficulty.ToString();
            txtTimer.Text = quesInf.Timer.ToString();
            txtRate.Value = quesInf.Rate;
            txtPicture.Text = quesInf.Picture;
            imgPic.ImageUrl = path + quesInf.Picture;
            cboANAL_Q0.Text = quesInf.ANAL_Q0;
            cboANAL_Q1.Text = quesInf.ANAL_Q1;
            cboANAL_Q9.Text = quesInf.ANAL_Q9;
            if (quesInf.Enabled == true)
            {
                rdlEnabled.SelectedIndex = 0;
            }
            else
                rdlEnabled.SelectedIndex = 1;
            if (quesInf.ID != 0 && quesInf.ID != -1)
                btnAnswer.Enabled = true;
        }

        protected void dgvList_ItemCommand(object sender, GridCommandEventArgs e)
        {
            if (e.CommandName.ToUpper() == "SELECTED")
            {
                string id = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString();
                BUS.QuestionControl ctr = new BUS.QuestionControl();
                SetDataToForm(ctr.Get(Convert.ToInt64(id), ref sErr));
                lbErr.Text = "";
            }
            if (e.CommandName.ToUpper() == "DETAIL")
            {
                string id = e.Item.OwnerTableView.DataKeyValues[e.Item.ItemIndex]["ID"].ToString();
                BUS.QuestionControl ctr = new BUS.QuestionControl();
                DTO.QuestionInfo info = ctr.Get(Convert.ToInt64(id), ref sErr);
                Session["question"] = info;
                Response.Redirect("Answers.aspx");
            }
        }

        protected void dgvList_NeedDataSource(object sender, GridNeedDataSourceEventArgs e)
        {
            BUS.QuestionControl ctr = new BUS.QuestionControl();
            DataTable dt = ctr.GetAll(ref sErr);
            BUS.LIST_DAControl daCtr = new BUS.LIST_DAControl();
            DTO.UserInfo usrinf = Session["UserAdmin"] as DTO.UserInfo;
            DataTable dtPermision = daCtr.GetPermissionByRole(usrinf.GroupCode, ref sErr);
            if (dtPermision.Rows.Count == 0)
                dt.Rows.Clear();
            for (int i = dt.Rows.Count - 1; i >= 0; i--)
            {
                DTO.QuestionInfo questInf = new DTO.QuestionInfo(dt.Rows[i]);
                string flag = "";
                bool ie = true;
                foreach (DataRow row in dtPermision.Rows)
                {
                    if (questInf.ANAL_Q9.Trim() != "")
                    {
                        if (questInf.ANAL_Q9 == row["DAG_ID"].ToString())
                        {
                            flag = row["EI"].ToString();
                        }
                        else if (row["EI"].ToString() == "I")
                        {
                            ie = false;
                        }
                    }
                }
                if ((flag == "" && ie) || flag == "I")
                {
                }
                else
                {
                    dt.Rows.Remove(dt.Rows[i]);
                }

            }
            dgvList.DataSource = dt;

        }

        protected void btnNew_Click(object sender, EventArgs e)
        {
            RefreshForm("");
        }

        protected void btnSave_Click(object sender, EventArgs e)
        {
            DTO.QuestionInfo quesInf = new DTO.QuestionInfo();
            quesInf = GetDataFromForm(quesInf);
            BUS.QuestionControl ctr = new BUS.QuestionControl();
            if (txtID.Text != "")
            {
                sErr = ctr.Update(quesInf);
                if (sErr != "")
                    lbErr.Text = sErr;
                else
                    lbErr.Text = "Update successfull";
            }
            else
            {
                txtID.Text = ctr.Add(quesInf, ref sErr).ToString();
                if (sErr != "")
                    lbErr.Text = sErr;
                else
                    lbErr.Text = "Insert successfull";
            }
            if (sErr == "")
                dgvList.Rebind();
        }

        protected void btnDelete_Click(object sender, EventArgs e)
        {
            foreach (GridItem item in dgvList.SelectedItems)
            {
                if (item.ItemIndex >= 0)
                {
                    string id = item.OwnerTableView.DataKeyValues[item.ItemIndex]["ID"].ToString();
                    BUS.QuestionControl ctr = new BUS.QuestionControl();
                    sErr = ctr.Delete(Convert.ToInt64(id));
                }
            }
            dgvList.Rebind();
        }

        protected void btnTransferIn_Click(object sender, EventArgs e)
        {
            int count = 0;
            if (upFile.UploadedFiles.Count > 0)
            {
                string filename = MapPath(upFile.TargetFolder + "/" + Path.GetFileName(upFile.UploadedFiles[0].FileName));
                TransferInQuestion(filename);
            }

        }

        private void TransferInQuestion(string filename)
        {
            try
            {
                int count = 0;
                if (File.Exists(filename))
                {
                    XlsFile xlsFile = new XlsFile(filename, true);

                    int indexRA = 2;
                    BUS.QuestionControl ctrQ = new BUS.QuestionControl();
                    BUS.AnswerControl ctrA = new BUS.AnswerControl();
                    for (int i = 2; i <= xlsFile.GetRowCount(1); i++)
                    {
                        DTO.QuestionInfo infQ = new DTO.QuestionInfo();
                        infQ = GetQuestion(infQ, xlsFile, i);
                        if (infQ.ID == 0)
                            break;
                        else
                            count++;
                        Int64 idQ_Old = infQ.ID;
                        Int64 idQ_New = ctrQ.Add(infQ, ref sErr);
                        if (sErr != "")
                            throw new Exception(sErr);
                        for (int j = 2; j <= xlsFile.GetRowCount(2); j++)
                        {
                            DTO.AnswerInfo infA = new DTO.AnswerInfo();
                            infA = GetAnswer(infA, xlsFile, j);
                            if (infA.ID == 0)
                                break;
                            if (infA.Question_ID == idQ_Old)
                            {
                                infA.Question_ID = idQ_New;
                                ctrA.Add(infA, ref sErr);
                                if (sErr != "")
                                    throw new Exception(sErr);
                            }
                            indexRA = j;
                        }
                    }
                    if (sErr == "")
                    {
                        lbErr.Text = "Transfer " + count + " records successfull!";
                    }
                }



            }
            catch (Exception ex)
            {
                lbErr.Text = ex.Message;
            }

        }

        private DTO.AnswerInfo GetAnswer(DTO.AnswerInfo ret, XlsFile xlsFile, int indexRow)
        {

            xlsFile.ActiveSheet = 2;
            for (int i = 1; i <= xlsFile.GetColCount(2); i++)
            {
                object obj = xlsFile.GetCellValue(1, i);
                if (obj != null)
                {
                    object val = xlsFile.GetCellValue(indexRow, i);
                    if (val != null)
                        switch (obj.ToString())
                        {
                            case "ID": ret.ID = Convert.ToInt64(val); break;
                            case "Question_ID": ret.Question_ID = Convert.ToInt64(val); break;
                            case "Description": ret.Description = Convert.ToString(val); break;
                            case "Explanation": ret.Explanation = Convert.ToString(val); break;
                            case "IsRight": ret.IsRight = Convert.ToBoolean(val); break;
                            case "Order_Answer": ret.Order_Answer = Convert.ToString(val); break;
                            case "Text_Answer": ret.Text_Answer = Convert.ToString(val); break;
                            case "Enabled": ret.Enabled = Convert.ToBoolean(val); break;
                            case "ANAL_A0": ret.ANAL_A0 = Convert.ToString(val); break;
                            case "ANAL_A1": ret.ANAL_A1 = Convert.ToString(val); break;
                            case "ANAL_A2": ret.ANAL_A2 = Convert.ToString(val); break;
                            case "ANAL_A3": ret.ANAL_A3 = Convert.ToString(val); break;
                            case "ANAL_A4": ret.ANAL_A4 = Convert.ToString(val); break;
                            case "ANAL_A5": ret.ANAL_A5 = Convert.ToString(val); break;
                            case "ANAL_A6": ret.ANAL_A6 = Convert.ToString(val); break;
                            case "ANAL_A7": ret.ANAL_A7 = Convert.ToString(val); break;
                            case "ANAL_A8": ret.ANAL_A8 = Convert.ToString(val); break;
                            case "ANAL_A9": ret.ANAL_A9 = Convert.ToString(val); break;

                        }
                }
                else throw new Exception("Format File is not correct");
            }
            return ret;
        }

        private DTO.QuestionInfo GetQuestion(DTO.QuestionInfo ret, XlsFile xlsFile, int indexRow)
        {
            xlsFile.ActiveSheet = 1;
            for (int i = 1; i <= xlsFile.GetColCount(1); i++)
            {
                object obj = xlsFile.GetCellValue(1, i);
                if (obj != null)
                {
                    object val = xlsFile.GetCellValue(indexRow, i);
                    if (val != null)
                        switch (obj.ToString())
                        {
                            case "ID": ret.ID = Convert.ToInt64(val); break;
                            case "Description": ret.Description = Convert.ToString(val); break;
                            case "Explanation": ret.Explanation = Convert.ToString(val); break;
                            case "Type": ret.Type = Convert.ToString(val); break;
                            case "Difficulty": ret.Difficulty = Convert.ToInt32(val); break;
                            case "Timer": ret.Timer = Convert.ToInt32(val); break;
                            case "Picture": ret.Picture = Convert.ToString(val); break;
                            case "Sound": ret.Sound = Convert.ToString(val); break;
                            case "Enabled": ret.Enabled = Convert.ToBoolean(val); break;
                            case "ANAL_Q0": ret.ANAL_Q0 = Convert.ToString(val); break;
                            case "ANAL_Q1": ret.ANAL_Q1 = Convert.ToString(val); break;
                            case "ANAL_Q2": ret.ANAL_Q2 = Convert.ToString(val); break;
                            case "ANAL_Q3": ret.ANAL_Q3 = Convert.ToString(val); break;
                            case "ANAL_Q4": ret.ANAL_Q4 = Convert.ToString(val); break;
                            case "ANAL_Q5": ret.ANAL_Q5 = Convert.ToString(val); break;
                            case "ANAL_Q6": ret.ANAL_Q6 = Convert.ToString(val); break;
                            case "ANAL_Q7": ret.ANAL_Q7 = Convert.ToString(val); break;
                            case "ANAL_Q8": ret.ANAL_Q8 = Convert.ToString(val); break;
                            case "ANAL_Q9": ret.ANAL_Q9 = Convert.ToString(val); break;
                        }
                }
                else throw new Exception("Format File is not correct");
            }
            return ret;
        }
        private void GetValue(ref DataRow newRow, string fieldName, XlsFile xlsFile, int top, int left, string fontCode)
        {
            try
            {
                if (!xlsFile.CellMergedBounds(top, left).IsOneCell)
                {
                    top = xlsFile.CellMergedBounds(top, left).Top;
                    left = xlsFile.CellMergedBounds(top, left).Left;
                }
                if (newRow.Table.Columns[fieldName].DataType == typeof(DateTime))
                    newRow[fieldName] = GetDateTimeObj(xlsFile, top, left);
                else
                    newRow[fieldName] = GetObject(xlsFile.GetCellValue(top, left), fontCode);
            }
            catch { throw new Exception("Object(" + xlsFile.ActiveSheetByName + "," + top + "," + left + ") is not valided"); }
        }
        private static object GetDateTimeObj(XlsFile xlsFile, int top, int left)
        {
            if (xlsFile.GetCellVisibleFormatDef(top, left).Format != "")
                return FlxDateTime.FromOADate((double)xlsFile.GetCellValue(top, left), false);
            else
            {
                Object obj = xlsFile.GetCellValue(top, left);
                if (obj is double)
                {
                    int sunDate = Convert.ToInt32(obj);
                    int year = sunDate / 10000;
                    int month = (sunDate - year * 10000) / 100;
                    int day = sunDate - year * 10000 - month * 100;
                    return new DateTime(year, month, day);
                }
                else
                    return DBNull.Value;
            }
        }
        private object GetObject(object p, string fontCode)
        {
            //object p = null;
            if (p == null || p.ToString().Trim().TrimStart() == "")
                return DBNull.Value;
            if (fontCode == "None" || fontCode == "Unicode")
            {
                //if (p is string)
                return p.ToString().Trim().TrimStart();
                //return p;
            }
            else
            {
                if (p is String)
                {
                    //if (fontCode == "TVCN3")
                    //    return VNConvertor.ConvertTCVN3ToUnicode(p.ToString().Trim().TrimStart());
                    //else if (fontCode == "VNI")
                    //    return VNConvertor.ConvertVNI2Unicode(p.ToString().Trim().TrimStart());
                    return p.ToString().Trim().TrimStart();
                }

            }
            return p;
        }

        protected void btnAnswer_Click(object sender, EventArgs e)
        {
            if (txtID.Text != "")
            {
                string id = txtID.Text;
                BUS.QuestionControl ctr = new BUS.QuestionControl();
                DTO.QuestionInfo info = ctr.Get(Convert.ToInt64(id), ref sErr);
                Session["question"] = info;
                Response.Redirect("Answers.aspx");
            }
        }

        private void LoadAnal(RadComboBox cbo, string cate)
        {
            BUS.SSRFANVControl ctr = new BUS.SSRFANVControl();
            DataTable dt = ctr.GetCategory_SSRFANV(_db, cate, ref sErr);
            cbo.DataSource = dt;
            cbo.DataTextField = "Code";
            cbo.DataValueField = "Code";
            cbo.DataBind();
        }

        protected void cboANAL_Q_SelectedIndexChanged(object sender, RadComboBoxSelectedIndexChangedEventArgs e)
        {

        }

        protected void cboANAL_Q9_ItemsRequested(object sender, RadComboBoxItemsRequestedEventArgs e)
        {

        }

    }
}
